package com.atom.plugin.flow

import com.android.build.gradle.AppExtension
import com.android.build.gradle.AppPlugin
import com.android.build.gradle.BaseExtension
import com.atom.plugin.core.Log
import com.atom.plugin.core.isTrue
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.ExtensionContainer
import org.gradle.api.plugins.PluginContainer
import java.util.*

abstract class AbstractFlowPlugin<E : AbstractFlowExtension> : Plugin<Project>, IFlow {

    protected lateinit var project: Project
    protected lateinit var extension: E
    protected lateinit var flowExtension: FlowExtension

    abstract fun getExtensionName(): String
    abstract fun getExtensionClass(): Class<E>

    final override fun apply(project: Project) {
        Log.init(project)
        Log.e("${getExtensionName()} Apply \nDate ${Date()}")
        this.project = project
        val plugins: PluginContainer = project.plugins
        // 主要是负责检查当前的plugin是否在android环境使用
        val hasAppPlugin: Boolean = plugins.hasPlugin(AppPlugin::class.java)
        hasAppPlugin.isTrue {
            val extensions: ExtensionContainer = project.extensions
            this.extension = extensions.create(getExtensionName(), getExtensionClass())
                ?: this.getExtensionClass().newInstance()
            this.flowExtension = extensions.create("FlowExtension", FlowExtension::class.java)
                ?: FlowExtension()
            project.afterEvaluate { p ->
                Log.setEnable(this.extension.enableUse)
                Log.setAbort(this.extension.abortError)
                Log.w("1 - 1 ${this.extension}")
                Log.w("1 - 2 $flowExtension")
            }
            Log.w("0 - 1 ${this.extension}")
            Log.w("0 - 2 $flowExtension")
        }
    }
}